<?php if (!defined('TL_ROOT')) die('You can not access this file directly!');

/**
 * TYPOlight webCMS
 * Copyright (C) 2005-2009 Leo Feyer
 *
 * This program is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation, either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this program. If not, please visit the Free
 * Software Foundation website at http://www.gnu.org/licenses/.
 *
 * PHP version 5
 * @copyright  Leo Feyer 2005-2009
 * @author     Leo Feyer <leo@typolight.org>
 * @package    Backend
 * @license    LGPL
 * @filesource
 */


/**
 * Class ModuleCatalogAttribute
 *
 * Back end module "maintenance".
 * @copyright  Leo Feyer 2005-2009
 * @author     Leo Feyer <leo@typolight.org>
 * @package    Controller
 */
class ModuleCatalogAttribute extends BackendModule
{

	/**
	 * Template
	 * @var string
	 */
	protected $strTemplate = 'be_catalog_attribute';


	/**
	 * Generate module
	 */
	protected function compile()
	{
		if (!$this->Input->get('act') || $this->Input->get('act') == 'list')
		{
			if (!$this->Input->get('key'))
				$this->generateAttributeList();
			else
			{
				if ($this->Input->get('key') == 'export_inventory')
					$this->exportInventory();
			}
		}
		else
		{
			switch ($this->Input->get('act'))
			{
				case 'create':
					if (!$this->Input->post('FORM_SUBMIT'))
						$this->generateAttrDetail();
					else
					{
						$insertId = $this->updateAttr();
						// judage the action.
						if ($this->Input->post('FORM_ACTION'))
						{
							switch ($this->Input->post('FORM_ACTION'))
							{
								case 'save':									
									$this->redirect("typolight/main.php?do=catalog_attribute&act=edit&id=$insertId");
									break;
								case 'saveNclose':
									$this->redirect("typolight/main.php?do=catalog_attribute&act=list&is_save=true");
									break;
								case 'saveNcreate':
									$this->redirect("typolight/main.php?do=catalog_attribute&act=create");
									break;
							}
						}
					}
					break;
				case 'edit':
					if (!$this->Input->post('FORM_SUBMIT'))
						$this->generateAttrDetail($this->Input->get('id'));
					else
					{
						$arr_id = $this->updateAttr($this->Input->get('id'));
						switch ($this->Input->post('FORM_ACTION'))
						{
							case 'save':									
								$this->redirect("typolight/main.php?do=catalog_attribute&act=edit&id=$arr_id");
								break;
							case 'saveNclose':
								$this->redirect("typolight/main.php?do=catalog_attribute&act=list");
								break;
							case 'saveNcreate':
								$this->redirect("typolight/main.php?do=catalog_attribute&act=create");
								break;
						}
					}
					break;
				case 'delete':
					if ($this->Input->get('id'))
					{
						$this->Database->prepare("DELETE FROM `tl_catalog_attribute` WHERE `id`=?")
										->execute($this->Input->get('id'));
						
						$this->redirect("typolight/main.php?do=catalog_attribute&act=list");
					}
					break;
				case 'show':
					$this->getShowDetail($this->Input->get('id'));
					break;
				default:
					break;
			}
		}
	}
	
	/**
	  * Export inventory list
	  * @params null
	  * @return null
	  */
	 private function exportInventory()
	 {
		$arrInventory = array();
		
		$objInventory = $this->Database->prepare("SELECT product_catalog.skuid, product_catalog.name, catalog_colour.title, catalog_size.size, tl_catalog_attribute.catalog_stock , product_catalog.`price` 
												FROM tl_catalog_attribute
												INNER JOIN product_catalog ON product_catalog.id=tl_catalog_attribute.id_catalog
												INNER JOIN catalog_colour ON catalog_colour.id=tl_catalog_attribute.id_color
												INNER JOIN catalog_size ON catalog_size.id=tl_catalog_attribute.id_size 	
												WHERE 1")
										->execute(time(), time());
		
		if ($objInventory->numRows < 1)
			return;
		
		$arrColumn[0] = array(
			'Skuid', 'Product Name', 'Colour', 'Size', 'Stock', 'Price'
		);
		
		while ($objInventory->next())
		{
			$arrInventory[] = array(
				'skuid' => $objInventory->skuid,
				'name' => $objInventory->name,
				'title' => $objInventory->title,
				'size' => $objInventory->size,
				'catalog_stock' => $objInventory->catalog_stock,
				'price' => $objInventory->price,
			);
		}
		
		$arrInventory = array_merge($arrColumn, $arrInventory);
		include_once(TL_ROOT."/plugins/phpexcel/excel-xml.php");
		$objExcel = Excel_XML_Generate::getInstance();
		$objExcel->generateExcel('invetory_' . date("Y-m-d"), $arrInventory);
	 }
	
	/**
	 * Generate the attribute list
	 * @params null
	 * @return null
	 */
	private function generateAttributeList()
	{
		//$strLimit = "LIMIT 0,30";
		$strLimit = "";
		$strWhere = "WHERE 1";
		$cnt = 0;
		$arrWildcards = array();
		$arrValues = array();
		$intLength = 0;
		
		if ($this->Input->post('FORM_SUBMIT'))
		{
			if ($this->Input->post('tl_limit'))
				if ($this->Input->post('tl_limit') == 'all')
					$strLimit = "";
				else
					$strLimit = "LIMIT " . $this->Input->post('tl_limit');
			
			// Save the session.
			if (!isset($_SESSION['CATALOGATTRIBUTELIST']['limit']) || !$_SESSION['CATALOGATTRIBUTELIST']['limit'] || $_SESSION['CATALOGATTRIBUTELIST']['limit'] != $strLimit)
				$_SESSION['CATALOGATTRIBUTELIST']['limit'] = $strLimit;
				
			if ($this->Input->post('tl_order_search') && $this->Input->post('tl_search_value'))
			{
				switch ($this->Input->post('tl_order_search'))
				{
					case 'skuid':
						//$strWhere .= " AND cata.`skuid` = '" . $this->Input->post('tl_search_value') . "'";
						$arrWildcards[] = "catalog.`skuid` LIKE ?";
						$arrValues[] = '%' . $this->Input->post('tl_search_value') . '%';
						break;
					default;
						break;
				}

				$this->Template->order_search = $this->Input->post('tl_order_search');
				$this->Template->search_value = $this->Input->post('tl_search_value');
				$strWhere = $strWhere . (($arrWildcards) ? " AND " . implode(' AND ', $arrWildcards) : "");
				if (!isset($_SESSION['CATALOGATTRIBUTELIST']['condition']) || !$_SESSION['CATALOGATTRIBUTELIST']['condition'] || $_SESSION['CATALOGATTRIBUTELIST']['condition'] != $strWhere)
					$_SESSION['CATALOGATTRIBUTELIST']['condition'] = $strWhere;
				if (!isset($_SESSION['CATALOGATTRIBUTELIST']['values']) || !$_SESSION['CATALOGATTRIBUTELIST']['values'] || $_SESSION['CATALOGATTRIBUTELIST']['values'] != serialize($arrValues))
					$_SESSION['CATALOGATTRIBUTELIST']['values'] = serialize($arrValues);
			}
		}
		else
		{
			if (isset($_GET['is_save']) && $_GET['is_save'] == 'true')
			{
				if ($_SESSION['CATALOGATTRIBUTELIST']['condition'])
					$strWhere = $_SESSION['CATALOGATTRIBUTELIST']['condition'];
				
				if ($_SESSION['CATALOGATTRIBUTELIST']['limit'])
					$strLimit = $_SESSION['CATALOGATTRIBUTELIST']['limit'];
					
				if ($_SESSION['CATALOGATTRIBUTELIST']['values'])
					$arrValues = unserialize($_SESSION['CATALOGATTRIBUTELIST']['values']);
			}
		}
		
		$objAttributes = $this->Database->prepare("SELECT COUNT(*) AS cnt 
													FROM `tl_catalog_attribute` AS attr 
													INNER JOIN `product_catalog` AS catalog ON catalog.`id`=attr.`id_catalog`
													INNER JOIN `catalog_colour` AS cata_color ON cata_color.`id`=attr.`id_color`
													INNER JOIN `catalog_size` AS cata_size ON cata_size.`id`=attr.`id_size`
													" . $strWhere . " 
													GROUP BY catalog.`skuid`, cata_color.`title`, cata_size.`size` 
													ORDER BY catalog.`skuid` ASC, cata_color.`title` ASC")
											->execute($arrValues, time(), time());
									
		$this->Template->total = $objAttributes->numRows;
		$this->Template->total_page = floor($this->Template->total/30);
		$this->Template->residue = $this->Template->total % 30;
		//$this->Template->limitValue = ($this->Input->post('tl_limit')) ? $this->Input->post('tl_limit') : "0,30";
		$this->Template->limitValue = ($this->Input->post('tl_limit')) ? $this->Input->post('tl_limit') : "all";
		
		$objCatalogAttribute = $this->Database->prepare("SELECT catalog.`name`, catalog.`skuid`, cata_color.`title`, cata_size.`size`, attr.`catalog_stock`, attr.`id` AS 'attr_id' 
														FROM `tl_catalog_attribute` AS attr
														INNER JOIN `product_catalog` AS catalog ON catalog.`id`=attr.`id_catalog`
														INNER JOIN `catalog_colour` AS cata_color ON cata_color.`id`=attr.`id_color`
														INNER JOIN `catalog_size` AS cata_size ON cata_size.`id`=attr.`id_size`
														" . $strWhere . "
														GROUP BY catalog.`skuid`, cata_color.`title`, cata_size.`size`
														ORDER BY catalog.`skuid` ASC, cata_color.`title` ASC 
														" . $strLimit)
											->execute($arrValues, time(), time());
										
		$arrCatalogAttrs = array();
		if ($objCatalogAttribute->numRows >= 1)
		{
			while($objCatalogAttribute->next())
			{
				$arrCatalogAttrs[] = array(
					'attr_id' => $objCatalogAttribute->attr_id,
					'skuid' => $objCatalogAttribute->skuid,
					'title' => $objCatalogAttribute->title,
					'size' => $objCatalogAttribute->size,
					'catalog_stock' => $objCatalogAttribute->catalog_stock,
				);
			}
		}
		$this->Template->attributes = $arrCatalogAttrs;
	}
	
	/**
	 * Generate the attribute detail
	 * @params string attr_id
	 * @return null
	 */
	private function generateAttrDetail($attr_id=0)
	{
		if (!$attr_id)
		{
			// create.
			$arrCurrent = array();
			$action = "create";
			// Get insert id.
		}
		else
		{
			$action = "edit";
			// edit.
			$objAttr = $this->Database->prepare("SELECT *
													FROM `tl_catalog_attribute`
													WHERE `id`=?")
										->execute($attr_id, time(), time());
			$arrCurrent = array();
			if ($objAttr->next())
			{
				$arrCurrent = array(
					'attr_id' => $attr_id,
					'id_catalog' => $objAttr->id_catalog,
					'id_color' => $objAttr->id_color,
					'id_size' => $objAttr->id_size,
					'catalog_stock' => $objAttr->catalog_stock,
				);
			}
		}
		
		$objCatalog = $this->Database->prepare("SELECT *
													FROM `product_catalog`
													ORDER BY `skuid`")
										->execute(time(), time());
		$arrCatalogs = array();
		while ($objCatalog->next())
		{
			$arrCatalogs[$objCatalog->id] = $objCatalog->skuid;
		}
		
		$objColor = $this->Database->prepare("SELECT *
												FROM `catalog_colour`
												ORDER BY `title`")
									->execute(time(), time());
		$arrColors = array();
		while ($objColor->next())
		{
			$arrColors[$objColor->id] = $objColor->title;
		}
		
		$objSize = $this->Database->prepare("SELECT *
												FROM `catalog_size`
												ORDER BY `size`")
									->execute(time(), time());
		$arrSize = array();
		while ($objSize->next())
		{
			$arrSize[$objSize->id] = $objSize->size;
		}
		
		$this->Template = new BackendTemplate("be_attrdetail");
		$this->Template->catalogs = $arrCatalogs;
		$this->Template->colors = $arrColors;
		$this->Template->sizes = $arrSize;
		if ($arrCurrent)
			$this->Template->current = $arrCurrent;
		else
			$this->Template->current = $_SESSION['CATALOG_ATTRIBUTES'];
		$this->Template->action = $action;
		$this->Template->attr_id = $attr_id;
	}
	
	/**
	 * Get the show detail
	 * @params int attr_id
	 * @return null
	 */
	private function getShowDetail($attr_id)
	{
		$objAttr = $this->Database->prepare("SELECT attr.`tstamp`, attr.`id_catalog`, attr.`id_color`, attr.`id_size`, attr.`catalog_stock`, cata.`skuid`, cata_cor.`title` AS cata_color, cata_s.`size` AS cata_size
													FROM `tl_catalog_attribute` AS attr
													INNER JOIN `product_catalog` AS cata ON cata.`id`=attr.`id_catalog`
													INNER JOIN `catalog_colour` AS cata_cor ON cata_cor.`id`=attr.`id_color`
													INNER JOIN `catalog_size` AS cata_s ON cata_s.`id`=attr.`id_size`
													WHERE attr.`id`=?")
										->execute($attr_id, time(), time());
		$arrCurrent = array();
		if ($objAttr->next())
		{
			$arrCurrent = array(
				'attr_id' => $attr_id,
				'id_catalog' => $objAttr->id_catalog,
				'id_color' => $objAttr->id_color,
				'id_size' => $objAttr->id_size,
				'catalog_stock' => $objAttr->catalog_stock,
				'tstamp' => date('Y-m-d H:i', $objAttr->tstamp),
				'skuid' => $objAttr->skuid,
				'cata_color' => $objAttr->cata_color,
				'cata_size' => $objAttr->cata_size,
			);
		}
		
		$this->Template = new BackendTemplate("be_attrshow");
		$this->Template->current = $arrCurrent;
	}
	
	/**
	 * Save the catalog attribute.
	 * @params string attr_id
	 * @return null
	 */
	private function updateAttr($attr_id=0)
	{
		if (!$attr_id)
		{
			// create.
			$objAttributes = $this->Database->prepare("INSERT INTO `tl_catalog_attribute` (`tstamp`, `id_catalog`, `id_color`, `id_size`, `catalog_stock`) VALUES (?, ?, ?, ?, ?)")
											->execute(time(), $_POST['id_catalog'], $_POST['id_color'], $_POST['id_size'], $_POST['catalog_stock']);
			$attr_id = $objAttributes->insertId;
		}
		else
		{
			// edit.
			$objAttributes = $this->Database->prepare("UPDATE `tl_catalog_attribute` SET `tstamp`=?, `id_catalog`=?, `id_color`=?, `id_size`=?, `catalog_stock`=? WHERE `id`=?")
											->execute(time(), $_POST['id_catalog'], $_POST['id_color'], $_POST['id_size'], $_POST['catalog_stock'], $attr_id);
		}
		
		$_SESSION['CATALOG_ATTRIBUTES'] = array(
			'id_catalog' => $_POST['id_catalog'],
			'id_color' => $_POST['id_color'],
			'id_size' => $_POST['id_size'],
		);
		
		return $attr_id;
	}
	 
}

?>